package com.xonro.common.histrans.sfeg.biz.fm;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.emm.util.DateUtil;
import com.actionsoft.sdk.local.SDK;
import com.xonro.common.histrans.base.ctx.BOCreateData;
import com.xonro.common.histrans.base.ctx.FileTransData;
import com.xonro.common.histrans.base.ctx.HistoryTransContext;
import com.xonro.common.histrans.base.model.HistoryTransLogModel;
import com.xonro.common.histrans.base.consts.SfegConst;
import com.xonro.common.histrans.sfeg.biz.CommTransBiz;
import com.xonro.common.histrans.sfeg.biz.common.SfegFundProcessTransBiz;
import com.xonro.common.histrans.sfeg.ctx.SfecProcessCreateContext;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:zhuw
 * @Description:
 * @Date 2022/4/15
 */
public class DailyPayTransBiz extends SfegFundProcessTransBiz {
    @Override
    protected void transProcess0(SfecProcessCreateContext historyTransContext) {
        String createUser = historyTransContext.getProcessCreateContext().getProcessInstanceModel().getCreateUser();
        String bindId = historyTransContext.getProcessCreateContext().getProcessInstanceModel().getId();
        Timestamp startTime = historyTransContext.getProcessCreateContext().getProcessInstanceModel().getStartTime();
        List<BOCreateData> boCreateDataList = new ArrayList<>();
        RowMap mainData = historyTransContext.getMainData();


        String mainBOId = UUIDGener.getUUID();
        HistoryTransLogModel logModel = new HistoryTransLogModel();
        historyTransContext.setHistoryTransLogModel(logModel);
        logModel.setBindId(bindId);
        logModel.setBpmBOId(mainBOId);
        logModel.setBpmTable("BO_XR_EFM_DAILY_PAY");
        logModel.setOuterTable("tb_MoneyInOutAll");
        logModel.setOuterPK(mainData.getString("id"));
        logModel.setOuterExt1(mainData.getString("applyCode"));
        logModel.setOuterExt2(mainData.getString("itemName"));
        logModel.setOuterExt3(mainData.getString("feeType"));
        BOCreateData mainBOCreateData = new BOCreateData();
        //MUST 添加主表
        boCreateDataList.add(mainBOCreateData);
        BO mainBO = new BO();
        mainBOCreateData.setBo(mainBO);
        mainBOCreateData.setCreateUser(createUser);
        mainBO.setCreateDate(startTime);
        mainBO.setUpdateDate(startTime);
        mainBO.setId(mainBOId);
        mainBO.set("APPLY_DATE", startTime);
        mainBO.set("YEAR", DateUtil.format(startTime, "yyyy"));
        mainBO.set("OA_NO", mainData.getString("applyCode"));
        mainBO.set("PAY_AMOUNT", mainData.getString("applyTotal"));
        mainBO.set("DEPARTMENT_ID", mainData.getString("applyDept"));
        mainBO.set("USER_ID", CommTransBiz.getInstance().getUserKY(mainData.getString("applyUser")));
        mainBO.set("APPLY_DATE", mainData.getDate("applyDate"));
        mainBO.set("ACTUAL_PAY_AMOUNT", mainData.getString("realTotal"));

        putProjectNo(mainData, mainBO);

        String payType;
        String oaPayType = mainData.getString("paytype");
        payType = transPayType(oaPayType);
        mainBO.set("PAY_TYPE", payType);
        String itemName = mainData.getString("itemName");
        //添加数据
        historyTransContext.getProcessCreateContext().setBoCreateDatas(boCreateDataList);

        //添加附件
        FileTransData fileTransData = new FileTransData();
        fileTransData.setBoId(mainBOId);
        //OA表订单编号
        fileTransData.setFkCode(mainData.getString("applyCode"));
        fileTransData.setProcessInstId(bindId);
        historyTransContext.getFileTransDatas().add(fileTransData);
        if (StringUtils.equals(itemName, "零星费用报销单")) {
            mainBOCreateData.setBoName("BO_XR_EFM_DAILY_PAY");
            logModel.setBpmTable("BO_XR_EFM_DAILY_PAY");
            fileTransData.setBoName("BO_XR_EFM_DAILY_PAY");
            fileTransData.setFieldName("ATTACHMENT");


            mainBO.set("BUSINESS_TYPE", "2");
            //TODO
            mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));
            mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));

            RowMap linkData = SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMap("SELECT * FROM tb_PointFeeExpenseAccount WHERE pfecCode = ?",
                    mainData.getString("applyCode"));
            if (linkData != null) {

                mainBO.set("PAY_AMOUNT_CAPITAL", linkData.getString("expenseTotalCapital"));

                List<RowMap> subDataList = SDK.getCCAPI().getRDSAPI(SfegConst.CCID)
                        .getMaps("SELECT * FROM tb_PointFeeExpenseAccountDetail WHERE pfecCode = ?",
                                mainData.getString("applyCode"));
                for (RowMap subData : subDataList) {
                    String uuid = UUIDGener.getUUID();
                    BOCreateData subBOCreateData = new BOCreateData();
                    boCreateDataList.add(subBOCreateData);
                    subBOCreateData.setCreateUser(createUser);
                    subBOCreateData.setBoName("BO_XR_EFM_DAILY_SPORADIC");
                    BO subBO = new BO();
                    subBO.setId(uuid);
                    subBOCreateData.setBo(subBO);
                    subBO.set("CONTENT", subData.getString("expenseContent"));
                    subBO.set("AMOUNT", subData.getString("expenseTotal"));
                    subBO.set("COUNT", subData.getString("billShare"));
                    super.addLogModel(historyTransContext, "tb_PointFeeExpenseAccountDetail", subData.getString("id"), "BO_XR_EFM_DAILY_SPORADIC", uuid, bindId);
                }
            } else {
                //市内交通
                snjt(historyTransContext, fileTransData, createUser, boCreateDataList, mainData, mainBO, bindId);
            }


        } else if (StringUtils.equals(itemName, "差旅费报销单")) {
            mainBOCreateData.setBoName("BO_XR_EFM_DAILY_PAY");
            fileTransData.setBoName("BO_XR_EFM_DAILY_PAY");
            logModel.setBpmTable("BO_XR_EFM_DAILY_PAY");
            fileTransData.setFieldName("ATTACHMENT");


            mainBO.set("BUSINESS_TYPE", "0");
            //TODO
            mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));
            mainBO.set("EXPENSE_TYPE", mainData.getString("feeType"));

            RowMap linkData = SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMap("SELECT * FROM tb_TravelExpenseAccount WHERE teaCode = ?",
                    mainData.getString("applyCode"));
            if (linkData != null) {
                mainBO.set("REASON", linkData.getString("addressAndReason"));
                mainBO.set("DAY", linkData.getString("hotelDayAmount"));
                mainBO.set("TRAVEL_AMOUNT", linkData.getString("hotelDayPrice"));
                mainBO.set("PAY_AMOUNT_CAPITAL", linkData.getString("expenseTotalCapital"));

            }
            List<RowMap> subDataList = SDK.getCCAPI().getRDSAPI(SfegConst.CCID)
                    .getMaps("SELECT * FROM tb_TravelExpenseAccountDetail WHERE teaCode = ?",
                            mainData.getString("applyCode"));
            for (RowMap subData : subDataList) {
                String uuid = UUIDGener.getUUID();
                BOCreateData subBOCreateData = new BOCreateData();
                boCreateDataList.add(subBOCreateData);
                subBOCreateData.setCreateUser(createUser);
                subBOCreateData.setBoName("BO_XR_EFM_DAILY_TRAVEL");
                BO subBO = new BO();
                subBOCreateData.setBo(subBO);
                subBO.setId(uuid);
                String travelStartTime = subData.getString("startTime");
                if (StringUtils.isNotBlank(travelStartTime)) {
                    try {
                        Date startDate=DateUtil.parse(travelStartTime, DateUtil.DATE_DFT_PATTERN);
                        if(startDate.getTime()>0){
                            subBO.set("START_DATE", startDate);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                String travelArriveTime = subData.getString("arriveTime");
                if (StringUtils.isNotBlank(travelArriveTime)) {
                    try {
                        Date arriveDate= DateUtil.parse(travelArriveTime, DateUtil.DATE_DFT_PATTERN);
                        if(arriveDate.getTime()>0) {
                            subBO.set("END_DATE",arriveDate);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                subBO.set("START_LOCATION", subData.getString("fromToAddress"));
                //TODO
                subBO.set("EXPENSE_TYPE", transTravelType(subData.getString("trafficType")));
                subBO.set("AMOUNT", subData.getString("trafficTotal"));
                subBO.set("DATE", subData.getString("livingDayAmount"));
                subBO.set("HOTEL_EXPENSE", subData.getString("livingPrice"));
                String trafficTotalStr = subData.getString("trafficTotal");
                String livingPriceStr = subData.getString("livingPrice");
                BigDecimal trafficTotal = StringUtils.isNoneBlank(trafficTotalStr) ? new BigDecimal(trafficTotalStr) : BigDecimal.ZERO;
                BigDecimal livingPrice = StringUtils.isNoneBlank(livingPriceStr) ? new BigDecimal(livingPriceStr) : BigDecimal.ZERO;
                subBO.set("TOTAL_AMOUNT", (trafficTotal.add(livingPrice)).toString());

                super.addLogModel(historyTransContext, "tb_TravelExpenseAccountDetail", subData.getString("id"), "BO_XR_EFM_DAILY_TRAVEL", uuid, bindId);

            }
        } else if (StringUtils.equals(itemName, "公司借款单")) {
            mainBOCreateData.setBoName("BO_XR_EFM_BORROW_APPLY");
            fileTransData.setBoName("BO_XR_EFM_BORROW_APPLY");
            logModel.setBpmTable("BO_XR_EFM_BORROW_APPLY");
            fileTransData.setFieldName("ATTACHMENT");
            RowMap loanData = SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMap("SELECT * FROM tb_CompanyLoanBill WHERE lbCode = ?",mainData.getString("applyCode"));
            List<RowMap> detailData = SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMaps("SELECT * FROM tb_CompanyLoanBillDetail WHERE lbCode = ?",mainData.getString("applyCode"));
            if(StringUtils.isNotBlank(mainData.getString("applyDate"))&&mainData.getString("applyDate").length()==10) {
                mainBO.set("APPLY_DATE", DateUtil.parse(mainData.getString("applyDate"), "yyyy-MM-dd"));//计划开工日期
            }
            mainBO.set("APPLY_NO",  mainData.getString("applyCode"));//申请单号
            mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));//费用类型编码
            mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));//费用类型编码
            mainBO.set("AMOUNT", mainData.getString("applyTotal"));//借款金额
            mainBO.set("OPERATION_DEPT", mainData.getString("applyDept"));//部门ID
            mainBO.set("OPERATOR", CommTransBiz.getInstance().getUserId( mainData.getString("applyUser")));//申请人
            mainBO.set("USER_ID", CommTransBiz.getInstance().getUserId( mainData.getString("applyUser")));//申请人
            mainBO.set("ACTUAL_PAY_AMOUNT", mainData.getDate("realTotal"));//实际金额
            mainBO.set("PAY_TYPE", mainData.getString("paytype"));//支付方式
            if (loanData != null) {
                mainBO.set("AMOUNT_CAPITAL", loanData.getString("loanTotalCapital"));//金额大写
                mainBO.set("REASON", loanData.getString("lbReason"));//借款用途
            }
            if(null!=detailData) {
                BigDecimal repaidAmount = BigDecimal.ZERO;
                for (RowMap subData : detailData) {
                    BigDecimal bigDecimal = new BigDecimal(subData.getString("total"));
                    repaidAmount = repaidAmount.add(bigDecimal);
                }
                mainBO.set("REPAID_AMOUNT", repaidAmount.toString());//还款金额
                mainBO.set("WRITE_OFF_AMOUNT", repaidAmount.toString());// 已冲销金额
            }
            mainBO.set("PROJECT_NO", mainData.getString("projid"));



        } else if (StringUtils.equals(itemName, "其它银行支付")) {
            mainBOCreateData.setBoName("BO_XR_EFM_OTHER_PAY");
            fileTransData.setBoName("BO_XR_EFM_OTHER_PAY");
            logModel.setBpmTable("BO_XR_EFM_OTHER_PAY");
            fileTransData.setFieldName("ATTACHMENT");


            mainBO.set("BUSINESS_TYPE", "0");
            //TODO
            mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));
            mainBO.set("EXPENSE_TYPE", mainData.getString("feeType"));

            RowMap linkData = SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMap("SELECT * FROM tb_CheckAccountReceive WHERE teaCode = ?",
                    mainData.getString("applyCode"));
            if (linkData != null) {
                mainBO.set("BANK_ACCOUNT", linkData.getString("applycircs2"));
                mainBO.set("PAY_CONTENT", linkData.getString("applycircs4"));
                mainBO.set("PAY_AMOUNT_CAPITAL", linkData.getString("totalCapital"));
                mainBO.set("BANK_NAME", linkData.getString("inBankSuggest"));
            }
            List<RowMap> subDataList = SDK.getCCAPI().getRDSAPI(SfegConst.CCID)
                    .getMaps("SELECT * FROM tb_CheckAccountReceiveDetail WHERE teaCode = ?",
                            mainData.getString("applyCode"));
            for (RowMap subData : subDataList) {
                String uuid = UUIDGener.getUUID();
                BOCreateData subBOCreateData = new BOCreateData();
                boCreateDataList.add(subBOCreateData);
                subBOCreateData.setCreateUser(createUser);
                subBOCreateData.setBoName("BO_XR_EFM_OTHER_PAY_LIST");
                BO subBO = new BO();
                subBOCreateData.setBo(subBO);
                subBO.setId(uuid);
                subBO.set("AMOUNT", subData.getString("expenseTotal"));
                subBO.set("CONTENT", subData.getString("wpname"));
                subBO.set("MODEL", subData.getString("gg"));
                subBO.set("UNIT", subData.getString("dw"));
                subBO.set("PRICE", subData.getString("danjia"));
                subBO.set("QUANTITY", subData.getString("sl"));

                super.addLogModel(historyTransContext, "tb_CheckAccountReceiveDetail", subData.getString("id"), "BO_XR_EFM_OTHER_PAY_LIST", uuid, bindId);

            }


        }
    }

    //TODO
    //业务费用类型
    private String transTravelType(String string) {
        return string;
    }

    private void snjt(SfecProcessCreateContext historyTransContext, FileTransData fileTransData, String
            createUser, List<BOCreateData> boCreateDataList, RowMap mainData, BO mainBO, String bindId) {


        mainBO.set("BUSINESS_TYPE", "2");
        //TODO
        mainBO.set("EXPENSE_TYPE_CODE", mainData.getString("feeType"));
        mainBO.set("EXPENSE_TYPE", mainData.getString("feeType"));

        RowMap linkData = SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMap("SELECT * FROM tb_TravelGWJTF WHERE id = ?",
                mainData.getString("applyCode"));
        if (linkData != null) {
            mainBO.set("PAY_AMOUNT_CAPITAL", linkData.getString("bxzjedx"));
            mainBO.set("PAY_CONTENT", linkData.getString("bz"));
        }

        List<RowMap> subDataList = SDK.getCCAPI().getRDSAPI(SfegConst.CCID)
                .getMaps("SELECT * FROM tb_TravelGWJTFDetail WHERE pid = ?",
                        mainData.getString("applyCode"));
        for (RowMap subData : subDataList) {
            String uuid = UUIDGener.getUUID();
            BOCreateData subBOCreateData = new BOCreateData();
            boCreateDataList.add(subBOCreateData);
            subBOCreateData.setCreateUser(createUser);
            subBOCreateData.setBoName("BO_XR_EFM_DAILY_TRAFFIC");
            BO subBO = new BO();
            subBO.setId(uuid);
            subBOCreateData.setBo(subBO);
            subBO.set("TRANSPORT", transTransport(subData.getString("jtgjcode")));
            if(StringUtils.isNotBlank(mainData.getString("outsj"))&&mainData.getString("outsj").length()==10) {
                mainBO.set("OUT_DATE", DateUtil.parse(mainData.getString("outsj"), "yyyy-MM-dd"));//计划开工日期
            }
            subBO.set("REASON", subData.getString("sy"));
            subBO.set("AMOUNT", subData.getString("je"));
            super.addLogModel(historyTransContext, "tb_TravelGWJTFDetail", subData.getString("id"), "BO_XR_EFM_DAILY_TRAFFIC", uuid, bindId);

        }
    }

    /*jtgj01
    jtgj02
    jtgj03
    jtgj99
    */
    private Object transTransport(String jtgjcode) {
        switch (jtgjcode) {
            case "jtgj01":
                return "01";
            case "jtgj02":
                return "02";
            case "jtgj03":
                return "03";
            case "jtgj99":
                return "04";
            default:
                return "";
        }
    }

    private void putProjectNo(RowMap mainData, BO mainBO) {
        mainBO.set("PROJECT_NAME", mainData.getString("projid"));
        mainBO.set("PROJECT_NO", mainData.getString("projid"));
    }

    //TODO, 和BPM中字典值不对应
    private String transPayType(String oaPayType) {
//        switch (oaPayType) {
//            case "现金":
//                return "1";
//            case "支票":
//                return "";
//            case "银行转帐":
//                return "";
//            case "其他支付方式":
//                return "4";
//            default:
//                return "";
//    }

        return oaPayType;
    }

    @Override
    protected String getProcessDefId(HistoryTransContext ctx) {
        RowMap mainData = ctx.getMainData();
        String itemName = mainData.getString("itemName");
        String processDefId;
        switch (itemName) {
            case "其它银行支付":
                processDefId="obj_701d7cacdeb444d080a308529bd74190";
                break;
            case  "公司借款单" :
                processDefId="obj_94acb51daa2c412c8a84a4305f0cb291";
                break;
             default:
                 processDefId="obj_2dda24e9c5434288a72831bd4687366c";
                 break;
        }

        return processDefId;
    }

    @Override
    protected String getActivityDefId(HistoryTransContext ctx) {
        RowMap mainData = ctx.getMainData();
        String itemName = mainData.getString("itemName");
        String activityDefId;
        switch (itemName) {
            case "其它银行支付":
                activityDefId="obj_198c003320c44af9bbc119b091a3b957";
                break;
            case  "公司借款单" :
                activityDefId="obj_6bf437e898654718a19abc20deeff04d";
                break;
            default:
                activityDefId="obj_749c8295ae204bdd935a574cda5ce28e";
                break;
        }

        return activityDefId;
    }

    @Override
    protected String getTitle(HistoryTransContext ctx) {
        RowMap mainData = ctx.getMainData();
        String itemName = mainData.getString("itemName");

        return itemName +  mainData.getString("applyCode");
    }


    @Override
    protected String getEnCode(HistoryTransContext ctx) {
        RowMap mainData = ctx.getMainData();
        return mainData.getString("applyCode");
    }

    @Override
    protected String getOuterTable(SfecProcessCreateContext historyTransContext) {
        return "tb_MoneyInOutAll";
    }

    @Override
    protected String getPk(SfecProcessCreateContext historyTransContext) {
        return historyTransContext.getMainData().getString("id");
    }


    @Override
    protected List<RowMap> getMainDatas() {
        return SDK.getCCAPI().getRDSAPI(SfegConst.CCID).getMaps("SELECT * FROM tb_MoneyInOutAll WHERE applycorp = '1040' and  itemName='其它银行支付' ");
    }

    @Override
    protected RowMap getMainData() {
        return null;
    }
}
